<?php
namespace control;
/*
*考试记录类
*/
class examRecordClass extends adIndexClass
{
    private const page = 'examRecord';
    private const table = 'topic_answer_record';
    private const title = '考试记录';

    /*财务管理-收支平衡-列表页-查询条件*/
    public function home()
    {
        $html =
            text(["name" => "createTime", "title" => L('topic.table.testStart').' - '.L('topic.table.testStart'), 'class'=>'text width200', 'laydate' => [ 'range' => '~'] ]).
            select(array("name" => "state","title" => L('recruitment.table.state'),"option" => array("合格","不合格"))).
            selectMultiple(["name" => "departmentId", 'table' => " department", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => L('staffProfiles.table.department')]).
            text(array("name" => "title","title" => L('topic.table.paperName'))).
            text(array("name" => "name","title" => L('staffProfiles.table.name')));
        //返回
        return $this->homeFun($this->search($html));
    }
    /*财务管理-收支平衡-列表页-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "name" => $this->post('name'),//姓名
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),   //状态
            "isCommit"      =>1,        //已提交试卷的
        );
        $and = '';
        if ($this->post('createTime')) {
            $timeArr = explode(' ~ ', $this->post('createTime'));
            $and .= " and date(startTime) >='{$timeArr[0]}' and date(startTime) <='{$timeArr[1]}'";
        }
        if (!empty($this->post('departmentId'))){
            //部门
            $and.=" and jobId in (select id from job where departmentId = '{$this->post('departmentId')}')";
        }
        if (!empty($this->post('title'))){
            //部门
            $and.=" and paperId in (select id from `paper_library` where name like '%{$this->post('title')}%')";
        }
        //获取查询结果
        $where = search(["like" => $like,"=" => $equal]).$and;
        $page = $this->page(array("table" => self::table, "where" => $where,"order" => "startTime desc,time desc"));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取表头
        $tr[] = ['', L('topic.table.testStart'), L('topic.table.paperName'), L('staffProfiles.table.department'), L('staffProfiles.table.job'), L('staffProfiles.table.name'), L('topic.table.paperScore'), L('topic.table.examScore'), L('recruitment.table.state')];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = "<span onclick=\"window.open('" . root . "control/adIndex.html?cla=paperManagement&fun=previewPaper&method=record&stid={$array['stid']}&id={$array['paperId']}')\"><img src='".root."img/control/preview.svg' class='listIco'></span>";
            //数据准备
            $job = query('job', " id = '$array[jobId]'");
            $department = query('department', " id = '$job[departmentId]'");
            $paper = query('paper_library'," id = '$array[paperId]'");
            $tr[] = [$dominate, $array['startTime'], $paper['name'],$department['name'],$job['name'], $array['name'],  $array['totalScore'], $array['score'], $array['state']];
        }
        $button="<span class='spanButton' onclick=\"layer('".self::page."','statistics',{})\">".L('topic.table.statisticalChart')."</span>";
        if ($this->power(self::page, "export")) {
            $button .= "<a href='" . root . "control/adIndex.html?cla=".$this->get('cla')."&fun=exportData' ><span class='spanButton'>".L('job.button.export')."</span></a>\n";
        }
        //返回
        $json['html'] = $page['hint'].$button."<form name='listForm'>".space.$this->tableMany(array("tr" => $tr))."</form>".$page['button'];
        $json['html'].=<<<eof
        <script src='{$this->root}static/javascript/echarts.min.js'></script>
		<script src='{$this->root}static/javascript/echarts.style.js'></script>
<script>

/**
 * 折线图
 * @param id DIV ID
 * @param name 图形名称
 * @param xAxis_data X轴数据
 * @param series_data Y轴数据
 */
function lineCharts(id, name, xAxis_data, series_data) {
    var myChart = echarts.init(document.getElementById(id));
    var option = {
        title: {
            text: name,
        },
      
        xAxis: {
            type: 'category',
            data: xAxis_data
        },
        tooltip: {
            show: true
        },
        yAxis: [{
            type: 'value',

        }],
        series: [{
            data: series_data,
            type: 'line',
        }]
    };
    // 指定图表的配置项和数据
    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);
}
</script>
eof;

        return json_encode($json, 320);
    }
    /*统计图*/
    public function statistics()
    {
        $text =selectMultiple(array('table'=>"staff",'name'=>'stid','sqlId'=>'stid','sqlField'=>'name','title'=>L('topic.table.staff')));
        $searchButton=L('topic.table.searchButton');
        $html = <<<efo
<div style="height: 50px;line-height: 50px;padding: 20px 0 0 76px;" class="search">{$text}<input class="searchSub" onclick="searchLine()" type="button" value="$searchButton"></div>
<div id="main" style="width: 1000px;height:550px;"></div>
<script>
 $(function() {
   searchLine();
 })

 function searchLine(){
     let stid = $("[name='stid']").val();
     $.post(root+'control/adIndex.html?cla=examRecord&fun=searchLine',{stid:stid},function(res) {
       lineCharts('main','',res.data.xData,res.data.yData);
     },'json')
 }
</script>
efo;
        return $this->layer(array("title" =>L('topic.table.statisticalChart'),"height" => 700,"width" => 1000,"html" => $html));
    }

    public function searchLine(){
        $stid = $this->post('stid');
        $xData = $yData = [];
        $result = find(array('table'=>'topic_answer_record','where'=>"isCommit = 1 and stid = '$stid'"));
        foreach ($result['array'] as $index =>$array){
            $xData[] = str_replace(['{{i}}'],[$index+1],L('topic.table.searchLine'));
            $yData[] = $array['score'];
        }
        $json['data'] = ['xData'=>$xData,'yData'=>$yData];
        return json_encode($json,320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = L('staffProfiles.tip.permission_export_warn');
        } else {
            $data = [];
            $sql = $_SESSION[self::page]['sql'];
            $title = [L('topic.table.testStart'), L('topic.table.paperName'), L('staffProfiles.table.department'), L('staffProfiles.table.job'), L('staffProfiles.table.name'), L('topic.table.paperScore'), L('topic.table.examScore'), L('recruitment.table.state')];
            $result = sqlFind($sql);
            if (is_array($result)) {
                foreach ($result as $array) {
                    //数据准备
                    $job = query('job', " id = '$array[jobId]'");
                    $department = query('department', " id = '$job[departmentId]'");
                    $paper = query('paper_library'," id = '$array[paperId]'");
                    $data[] = [$array['startTime'], $paper['name'],$department['name'],$job['name'], $array['name'],  $array['totalScore'], $array['score'], $array['state']];
                }
            }
            $text = str_replace(['{{staffName}}'],[$this->control['name']],L('topic.table.examRecordExport'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, L('topic.table.examRecord').".xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }
}
